package Leetcode;

import java.util.*;

/**
 * @ Author     ：侯耀祖
 * @ Description：
 */
public class orangesRotting {
    public int orangesRotting(int[][] grid) {
        int rows = grid.length;
        int cols = grid[0].length;
        Queue<int[]> queue = new LinkedList<>();
        int fresh = 0;
        int minutes = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (grid[i][j] == 1){
                    fresh++;
                } else if (grid[i][j] == 2){
                    queue.add(new int[]{i, j});
                }
            }
        }
        if (fresh == 0){
            return 0;
        }
        if (queue.isEmpty()){
            return -1;
        }
        int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        while (!queue.isEmpty() && fresh > 0){
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                int[] index = queue.poll();
                for (int[] dir : dirs) {
                    int x = index[0] + dir[0];
                    int y = index[1] + dir[1];
                    if (x >= 0 && y >= 0 && x < rows && y < cols && grid[x][y] == 1){
                        grid[x][y] = 2;
                        queue.offer(new int[]{x, y});
                        fresh--;
                    }
                }
            }
            minutes++;
        }
        return fresh == 0 ? minutes : -1;
    }
}
